package com.swim.pay.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.swim.common.utils.ConstantUtil;
import com.swim.common.utils.HttpUtil;
import com.swim.common.utils.WXPayUtil;
import com.swim.pay.bean.AliPayBean;
import com.swim.pay.service.PayService;

import lombok.extern.slf4j.Slf4j;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author tql
 * @Description PayServiceImpl
 * @Date 21-3-12 下午3:20
 * @Version 1.0
 */
@Slf4j
@Service
public class PayServiceImpl implements PayService {
	
    private Logger logger = LoggerFactory.getLogger(PayServiceImpl.class);

    @Override
    public Map<String, String> getWeixinPayCodeUrl(String outTradeNo, String totalFee, String tradeType) {
        Map<String, String> resultMap = new HashMap<String, String>();
        System.out.println("进入getWeixinPayCodeUrl方法");
        logger.info("进入getWeixinPayCodeUrl方法");
        int Fee = (int) (Double.parseDouble(totalFee) * 100);
        // 参数分装
        Map<String, String> paramMap = new HashMap<String, String>();
        // 微信开发平台应用id ok
        paramMap.put("appid", ConstantUtil.APP_ID);
        // 财付通商户号
        paramMap.put("mch_id", ConstantUtil.PARTNER_ID);
        // 随机字符串
        paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
        // 随意填(目前我没发现有啥用)
        paramMap.put("body", "EStore");
        // 订单号
        paramMap.put("out_trade_no", outTradeNo);
        // 金额
        paramMap.put("total_fee", String.valueOf(Fee));
        // 终端ip(用不着)
        paramMap.put("spbill_create_ip", "127.0.0.1");
        // 通知地址(我这里采取的监测订单的方式,这个可以选择不填)
        paramMap.put("notify_url", "127.0.0.1");
        // 交易类型(扫码支付)
        paramMap.put("trade_type", tradeType);//JSAPI--JSAPI支付（或小程序支付）、NATIVE--Native支付、APP--app支付，MWEB--H5支付，不同trade_type决定了调起支付的方式，请根据支付产品正确上传
        String paramXml = null;
        try {
            paramXml = WXPayUtil.generateSignedXml(paramMap, ConstantUtil.PARTNER_KEY);
            System.out.println("微信支付下单接口返回入参:"+paramXml);
            logger.info("微信支付下单接口返回入参:{}", paramXml);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 发送请求
        String xmlResult = HttpUtil.postData(ConstantUtil.UFDODER_URL, paramXml);
        System.out.println("微信支付下单接口返回:"+xmlResult);
        logger.info("微信支付下单接口返回:{}", xmlResult);
        Map<String, String> stringMap = null;
        try {
            stringMap = WXPayUtil.xmlToMap(xmlResult);
            System.out.println("微信支付下单接口返回结果:"+JSON.toJSONString(stringMap));
            logger.info("微信支付申请结果:{}", JSON.toJSONString(stringMap));
        } catch (Exception e) {
            e.printStackTrace();
        }
        //获取结果
        resultMap.put("status", "success");
        resultMap.put("code_url", stringMap.get("code_url")); //该url用于和微信支付对接(装载进二维码中即可)
        resultMap.put("out_trade_no", outTradeNo);
        resultMap.put("total_fee", totalFee);
        return resultMap;
    }

    @Override
    public Map<String, String> queryWeixinPayStatus(String outTradeNo) {
        //封装参数
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("appid", ConstantUtil.APP_ID);
        paramMap.put("mch_id", ConstantUtil.PARTNER_ID);
        paramMap.put("out_trade_no", outTradeNo);
        paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
        String paramXml = null;
        try {
            paramXml = WXPayUtil.generateSignedXml(paramMap, ConstantUtil.PARTNER_KEY);
            //发送请求
            String xmlResult = HttpUtil.postData(ConstantUtil.SELECT_URL, paramXml);
            //获取结果
            Map<String, String> stringMap = WXPayUtil.xmlToMap(xmlResult);
            return stringMap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public String mreadPaymentRequest(AliPayBean aliPayBean) {
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        // 同步通知路径(支付成功页面回调地址)
        alipayRequest.setReturnUrl(String.format(ConstantUtil.return_url, aliPayBean.getOutTradeNo()));
        // 异步通知路径(支付成功业务回调地址)
        alipayRequest.setNotifyUrl(ConstantUtil.notify_url);

        // 订单号
        String outTradeNo = aliPayBean.getOutTradeNo();
        // 价格
        Double price = aliPayBean.getTotalFee();
        String subject = aliPayBean.getSubject();
        String desc = aliPayBean.getDesc();

        // 业务参数
        Map<String, String> params = new HashMap<String, String>(16);
        params.put("out_trade_no", outTradeNo);
        params.put("total_amount", String.format("%.2f", price));
        params.put("subject", subject);
        params.put("body", desc);
        params.put("product_code", "FAST_INSTANT_TRADE_PAY");
        params.put("passback_params", "");
        // 调用
        alipayRequest.setBizContent(JSON.toJSONString(params));
        logger.info("支付宝参数:{}",JSON.toJSONString(params));
        logger.error("支付宝参数:{}", JSON.toJSONString(params));

        String result = "";
        try {
            AlipayClient alipayClient = new DefaultAlipayClient(
                    ConstantUtil.gatewayUrl,
                    ConstantUtil.ali_app_id,
                    ConstantUtil.alipay_private_key,
                    ConstantUtil.format,
                    ConstantUtil.charset,
                    ConstantUtil.alipay_public_key,
                    ConstantUtil.sign_type);

            AlipayTradePagePayResponse alipayResponse = alipayClient.pageExecute(alipayRequest);
            if (alipayResponse.isSuccess()) {
                result = alipayResponse.getBody();
            } else {
                logger.error("payment form error : {}", alipayResponse.getSubMsg());
                result = "ERROR";
            }
        } catch (Exception e) {
            logger.error(" payment error : {}", e.getMessage());
            e.printStackTrace();
        }
        return result;
    }
}
